﻿using SqlSugar;

namespace SqlSugarHelper
{
    internal class SqlClientFactory : ISqlClientFactory
    {
        private IDBConfig _Config;
        private SqlSugarClient _DbClient;

        [System.ThreadStatic]
        private static SqlSugarClient _Current = null;

        public SqlClientFactory(IDBConfig config)
        {
            this._Config = config;
        }
        protected SqlSugarClient DbClient
        {
            get
            {
                if (this._DbClient == null)
                {
                    this._DbClient = new SqlSugarClient(_Config.Configs);
                }
                return this._DbClient;
            }
        }
        public bool IsTran => _Current != null;

        public SqlSugarClient Current { get => _Current;  }

        public void BeginTran()
        {
            if (_Current == null)
            {
                _Current = this.DbClient;
                _Current.BeginTran();
            }
        }
        public void CommitTran(SqlSugarClient client)
        {
            if (_Current != null)
            {
                _Current.CommitTran();
                _Current = client;
            }
        }
        public void RollbackTran(SqlSugarClient client)
        {
            if (_Current != null)
            {
                _Current.RollbackTran();
                _Current = client;
            }
        }
        public SqlSugarProvider GetProvider(string name)
        {
            if (_Current != null)
            {
                return _Current.GetConnection(name);
            }
            return this.DbClient.GetConnection(name);
        }



        public ISugarQueryable<T> GetQueryable<T>(string name)
        {
            return this.DbClient.GetConnection(name).Queryable<T>();
        }
    }
}
